//
//  UIUtils.m
//  p2p
//
//  Created by mokai on 14-8-13.
//  Copyright (c) 2014年 cloudyoo. All rights reserved.
//

#import "UIUtils.h"

@implementation UIUtils



+(UIViewController *)currentViewController{
    UIViewController *ctr = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    if ([ctr isKindOfClass:[UINavigationController class]]) {
        return ((UINavigationController *)ctr).topViewController;
    }else{
        return nil;
    }
}

+(UIViewController *)currentViewWithClass:(Class)clazz
{
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    NSArray *ctrs = nav.viewControllers;
    for (UIViewController *ctr in ctrs) {
        if ([ctr isKindOfClass:clazz]) {
            return ctr;
            break;
        }
    }
    return nil;
}

+(void)popToViewContorllerWithClass:(Class)clazz{
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    NSArray *ctrs = nav.viewControllers;
    for (UIViewController *ctr in ctrs) {
        if ([ctr isKindOfClass:clazz]) {
            [nav popToViewController:ctr animated:YES];
            break;
        }
    }
}

+(void)popToViewContorllerWithCount:(int)count{
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    NSArray *ctrs = nav.viewControllers;
    [nav popToViewController:ctrs[ctrs.count-count-1] animated:YES];
}

+(void)pushViewController:(UIViewController *)ctr{
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    [nav pushViewController:ctr animated:YES];
}

//TextField 焦点相关
+(void)nextBecomeFirstResponderWithCurrentTextField:(UITextField *)current{
    UIView *view = [current.superview viewWithTag:current.tag+1];
    if ([view isKindOfClass:[UITextField class]]) {
        UITextField *next = (UITextField *)view;
        [self _nextBecomFirstListener:current next:next];
    }
}

+(void)nextBecomeFirstResponderWithCurrentTextField:(UITextField *)current nextTextField:(UITextField *)next{
    if (current!=nil && next!=nil) {
        [self _nextBecomFirstListener:current next:next];
    }
}
static NSMutableDictionary *responsders;
+(void)_initresponsders{
    if (responsders==nil) {
        responsders = [NSMutableDictionary dictionaryWithCapacity:5];
    }
}

+(void)_nextBecomFirstListener:(UITextField *)current next:(UITextField *)next{
    [self _initresponsders];
    [responsders setObject:next forKey:current];
    [current addTarget:self action:@selector(_nextBecomFirst:) forControlEvents:UIControlEventEditingDidEndOnExit];
}

+(void)_nextBecomFirst:(UITextField *)current{
    UITextField *next = [responsders objectForKey:current];
    [next becomeFirstResponder];
}
//Done





@end
